<?php
namespace App\Service\ApiXcx;

use Illuminate\Support\Facades\DB;

class GoodsService extends BaseService
{
    //商品

    /**
     * 分类列表
     * @return array
     */
    public function getCateList()
    {
        $db = DB::table($this->dbGcate)
            ->where('del', 0)
            ->where('pid', 0);
        $total = $db->count();
        $res = $db->skip(0)->take(4)->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有数据', 'data' => []);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $imglink = $v['img'] ? env('DOMAIN') . '/' . $v['img'] : '';
            $arys[] = [
                'id' => $v['id'],
                'img' => $imglink,
                'title' => $v['title'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 商品列表
     * @param array $pages【start，limit】
     * @param int $cateid 分类ID
     * @param array $pas【is_sale，is_price，is_new】
     * @param int $uid
     * @return array
     */
    public function getGoodsList($pages, $cateid, $keyword, $pas = [], $uid = 0)
    {
//        $this->setPriceBySku();
        $this->setShelfByStock();
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbGoods)->where('del', 0)->where('is_shelf', 1);
        if ($cateid) {
            $db = $db->where('cate_id', $cateid);
        }
        if ($keyword) {
            $db = $db->where('title', 'like', '%'.$keyword.'%');
        }
        if (isset($pas['is_new']) && $pas['is_new']) {
            $db = $db->where('isnew', 'like',1);
        }
        $total = $db->count();
        $db = $db->skip($start)->take($pages['limit']);
        if (isset($pas['is_sale']) && $pas['is_sale']) {
            $isSale = $pas['is_sale']==1 ? 'desc' : 'asc';
            $db = $db->orderBy('sale', $isSale);
        }
        if (isset($pas['is_price']) && $pas['is_price']) {
            $isPrice = $pas['is_price']==1 ? 'desc' : 'asc';
            $db = $db->orderBy('price', $isPrice);
        }
        $res = $db->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有数据', 'data' => [], 'total' => $total);
        }
        $discount = $this->discountByUid($uid);
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //分类
            $cateOne = (array) $this->dbConn($this->dbGcate)->where('id', $v['id'])->first();
            //限时折扣
            $cheap = $this->cheapByGid($v['id']);
            if ($cheap < $discount) {
                $discountNew = $cheap;
            } else {
                $discountNew = $discount;
            }
            //价格
            $skuid = $price = $price_line = $skuPrice = 0;
            $skuOne = (array) $this->dbConn($this->dbGsku)->where('del', 0)
                ->where('gid', $v['id'])
                ->orderBy('price', 'asc')
                ->first();
            if (!empty($skuOne)) {
                $skuid = $skuOne['id'];
                $price = $skuOne['price'] * $discountNew;
                $price_line = $skuOne['price_line'];
                $skuPrice = $skuOne['price'];
            }
            $arys[] = [
                'id' => $v['id'],
                'gno' => $v['gno'],
                'title' => $v['title'],
                'cate_id' => $v['cate_id'],
                'cateName' => $cateOne ? $cateOne['title'] : '',
                'img' => env('DOMAIN'). '/' . $v['bigimg'],
                'sku_id' => $skuid,
                'price' => toNumber($price),
                'price_line' => toNumber($price_line),
                'sale' => $v['sale'],
                'isnew' => $v['isnew'],
                'cartNum' => $this->getCartTotal($uid, $v['id']),
                'is_cheap' => $cheap==1 ? 0 : 1,
                'part' => 'chengfen',
                'discount' => $discountNew,
                'skuPrice' => $skuPrice,
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    //购物车数量
    public function getCartTotal($uid, $gid)
    {
        if (!$uid) {
            return 0;
        }
        return DB::table($this->dbCart)->where('del', 0)
            ->where('uid', $uid)
            ->where('gid', $gid)
            ->where('isorder', 0)
            ->sum('num');
    }

    //商品选项
    public function getOption()
    {
        $arys = ['delivery' => [], 'shop' => []];
        //配送方式
        $deliverys = $this->orderDeliverys;
        foreach ($deliverys as $k => $v) {
            $arys['delivery'][] = [
                'id' => $k,
                'title' => $v,
            ];
        }
        //门店
        $shopOnes = DB::table($this->dbShop)->where('del', 0)->get();
        if (count($shopOnes)) {
            foreach ($shopOnes as $v) {
                $v = (array) $v;
                $arys['shop'][] = [
                    'id' => $v['id'],
                    'title' => $v['shop_name'] . '-' . $v['address'],
                ];
            }
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    //商品详情
    public function getGoodsOne($gid, $uid)
    {
        $arys['gid'] = $gid;
        $arys['gprice'] = 0;
        $arys['gprice_line'] = 0;
        $arys['gsale'] = 0;
        $discount = $this->discountByUid($uid);
        //商品详情
        $gOne = (array) DB::table($this->dbGoods)->where('id', $gid)->first();
        if (empty($gOne)) {
            return $this->toback(-2, '没有记录');
        }
        //限时折扣
        $cheap = $this->cheapByGid($gOne['id']);
        if ($cheap < $discount) {
            $discount = $cheap;
        }
        $arys['is_cheap'] = $cheap==1 ? 0 : 1;
        $arys['gname'] = $gOne['title'];
        $arys['gprice'] = toNumber(($gOne['price'] * $discount));
        $arys['gsale'] = $gOne['sale'];
        $arys['gdetail'] = $gOne['detail'] ? htmlspecialchars_decode($gOne['detail']) : '';
        $arys['skuPrice'] = $gOne['price'];
        //商品图片
        $gImgs = DB::table($this->dbGimg)->where('del', 0)->where('gid', $gid)->get();
        if (count($gImgs)) {
            foreach ($gImgs as $v) {
                $v = (array) $v;
                $arys['gimgs'][] = env('DOMAIN') . '/' . $v['link'];
            }
        }
        //SKU
        $skuOnes = DB::table($this->dbGsku)->where('del', 0)
            ->where('gid', $gid)
            ->orderBy('price', 'asc')
            ->get();
        if (count($skuOnes)) {
            foreach ($skuOnes as $v) {
                $v = (array) $v;
                $arys['skuList'][] = [
                    'sku_id' => $v['id'],
                    'sku_name' => $v['title'],
                    'price' => toNumber(($v['price'] * $discount)),
                    'price_line' => toNumber($v['price_line']),
                ];
            }
            $v0 = (array) $skuOnes[0];
            $arys['gprice'] = toNumber(($v0['price'] * $discount));
            $arys['gprice_line'] = toNumber($v0['price_line']);
            $arys['skuPrice'] = $v0['price'];
            if ((isset($gOne['price']) && !$gOne['price']) && $arys['gprice']) {
                DB::table($this->dbGoods)->where('id', $gid)->update(['price'=>$arys['gprice']*100]);
            }
        }
        $arys['discount'] = $discount;
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    //关键词获取
    public function getKeywordList($uid)
    {
        $db = DB::table($this->dbGkeyword)
            //->distinct('word')
            ->where('del', 0)
            ->where('uid', $uid)
            ->groupBy('word');
        $total = $db->count();
        $res = $db->skip(0)->take(4)->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有搜索词', 'data' => [], 'total' => 0);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $total = DB::table($this->dbGkeyword)
                ->where('del', 0)
                ->where('uid', $uid)
                ->where('word', $v['word'])
                ->count();
            if ($v) {
                $arys[] = [
                    'id' => $v['id'],
                    'title' => $v['word'],
                    'total' => $total,
                ];
            }
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' =>$total);
    }

    /**
     * 关键词记录
     * @param int $uid
     */
    public function addKeyword($word, $uid)
    {
        return DB::table($this->dbGkeyword)->insertGetId([
            'uid' => $uid,
            'word' => $word,
            'addtime' => toDate(),
        ]);
    }

    /**
     * 关键词清理
     * @param int $uid
     **/
    public function keywordBatchDel($uid)
    {
        return DB::table($this->dbGkeyword)
            ->where('uid', $uid)
            ->update([
                'del' => 1,
                'deltime' => toDate(),
            ]);
    }

    /**
     * SKU列表
     * @param array $pages【start，limit】
     * @param int $gid
     * @return array
     */
    public function getSkuList($pages, $gid)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbGsku)->where('del', 0)->where('gid', $gid);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有数据', 'data' => []);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $arys[] = [
                'sku_id' => $v['id'],
                'title' => $v['title'],
                'price' => toNumber($v['price']),
                'price_line' => toNumber($v['price_line']),
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 浏览记录
     * @param int $uid
     * @param int $gid
     * @param int $skuid
     */
    public function setRead($uid, $gid, $skuid)
    {
        $arys = [
            'uid' => $uid,
            'gid' => $gid,
            'sku_id' => $skuid,
            'addtime' => toDate(),
        ];
        $res = DB::table($this->dbUtrace)->insertGetId($arys);
        if (!$res) {
            return array('code' => -2, 'msg' => '该用户不存在');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 浏览记录
     * @param int $uid
     * @param array $days【start，end】
     */
    public function getTraceList($uid, $days)
    {
        $res = DB::table($this->dbUtrace)
            ->where('uid', $uid)
            ->where('addtime', '>=', $days['start'])
            ->where('addtime', '<=', $days['end'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有历史数据', 'data' => []);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //商品信息
            $gOne = (array) DB::table($this->dbGoods)
                //->distinct('gid')
                ->where('del', 0)
                ->where('id', $v['gid'])
                ->first();
            $gname = empty($gOne) ? '' : $gOne['title'];
            $gimg = empty($gOne) ? '' : $gOne['bigimg'];
            //SKU信息
            $skuDB = DB::table($this->dbGsku)
                ->where('del', 0)
                ->where('gid', $v['gid']);
            if ($v['sku_id'] > 0) {
                $skuDB = $skuDB->where('id', $v['sku_id']);
            } else {
                $skuDB = $skuDB->orderBy('id', 'asc');
            }
            $skuOne = (array) $skuDB->first();
            $price = empty($skuOne) ? 0 : $skuOne['price'];
            $sku_name = empty($skuOne) ? '' : $skuOne['title'];
            //看看商品是否删除了
            $gOne = (array) $this->dbConn($this->dbGoods)
                ->where('del', 0)
                ->where('id', $v['gid'])
                ->first();
            $arys[] = [
                'id' => $v['id'],
                'gid' => $v['gid'],
                'sku_id' => $v['sku_id'],
                'gname' => $gname,
                'gimg' => env('DOMAIN') . '/' . $gimg,
                'price' => toNumber($price),
                'unit' => $sku_name,
                'cartNum' => $this->getCartTotal($uid, $v['id']),
                'gdel' => empty($gOne) ? 1 : 0,
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    /**
     * 通过SKU更新商品价格
     */
    public function setPriceBySku($gid = 0)
    {
        if ($gid) {
            $skuOne = (array) $this->dbConn($this->dbGsku)
                ->where('del', 0)
                ->where('gid', $gid)
                ->orderBy('price', 'asc')
                ->first();
            if (!empty($skuOne)) {
                $this->dbConn($this->dbGoods)->where('id', $gid)->update(['price' => $skuOne['price']]);
            }
            return true;
        }
        $gOnes = $this->dbConn($this->dbGoods)
            ->where('del', 0)
            ->get();
        if (count($gOnes)) {
            foreach ($gOnes as $v) {
                $gid = $v->id;
                $skuOne = (array) $this->dbConn($this->dbGsku)
                    ->where('del', 0)
                    ->where('gid', $gid)
                    ->orderBy('price', 'asc')
                    ->first();
                if (!empty($skuOne)) {
                    $this->dbConn($this->dbGoods)->where('id', $gid)->update(['price' => $skuOne['price']]);
                }
            }
        }
        return true;
    }

    //通过库存，更新商品下架
    public function setShelfByStock()
    {
        $gids = [];
        $res = $this->dbConn($this->dbGsku)
            ->where('del', 0)
            ->where('stock', 0)
            ->get();
        if (count($res)) {
            foreach ($res as $v) {
                $v = (array) $v;
                $skuOne = (array) $this->dbConn($this->dbGsku)
                    ->where('del', 0)
                    ->where('gid', $v['gid'])
                    ->where('stock', '>', 0)
                    ->first();
                if (empty($skuOne) && !in_array($v['gid'], $gids)) {
                    $gids[] = $v['gid'];
                }
            }
            $this->dbConn($this->dbGoods)->whereIn('id', $gids)->update(['is_shelf' => 0]);
        }
        return true;
    }
}